package com.usefullc.proxy.utils;

import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
import org.bouncycastle.asn1.x509.Extension;
import org.bouncycastle.asn1.x509.ExtensionsGenerator;
import org.bouncycastle.asn1.x509.GeneralName;
import org.bouncycastle.asn1.x509.GeneralNames;
import org.bouncycastle.openssl.jcajce.JcaPEMWriter;
import org.bouncycastle.operator.ContentSigner;
import org.bouncycastle.operator.OperatorCreationException;
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
import org.bouncycastle.pkcs.PKCS10CertificationRequest;
import org.bouncycastle.pkcs.PKCS10CertificationRequestBuilder;
import org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder;

import javax.security.auth.x500.X500Principal;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.security.*;

/**
 * @author: Sampson
 * @date: 2022-08-01 19:57
 */
public class GenCertUtils {

    public static void main(String[] args) throws OperatorCreationException, NoSuchAlgorithmException, IOException {
        // 创建密钥对
        KeyPairGenerator gen = KeyPairGenerator.getInstance("EC");
//        gen.initialize(571);
        KeyPair pair = gen.generateKeyPair();
        PrivateKey privateKey = pair.getPrivate();
        PublicKey publicKey = pair.getPublic();

        /**
         *  准备生成CA证书
         */
        // 创建 CSR 对象
        X500Principal subject = new X500Principal("C=usefullc, ST=usefullc, L=usefullc, O=usefullc, OU=usefullc, CN=usefullc, EMAILADDRESS=Sampson@usefullc.com");
        ContentSigner signGen = new JcaContentSignerBuilder("SHA256withECDSA").build(privateKey);
//        ContentSigner signGen = new JcaContentSignerBuilder("SHA256withRSA").build(privateKey);
        PKCS10CertificationRequestBuilder builder = new JcaPKCS10CertificationRequestBuilder(subject, publicKey);
        // 添加 SAN 扩展
        ExtensionsGenerator extensionsGenerator = new ExtensionsGenerator();
        GeneralNames generalNames = new GeneralNames(new GeneralName[]{new GeneralName(GeneralName.rfc822Name, "domain=usefullc.com"), new GeneralName(GeneralName.rfc822Name, "Sampson@usefullc.com")});
        extensionsGenerator.addExtension(Extension.subjectAlternativeName, false, generalNames);
        builder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, extensionsGenerator.generate());
        // build csr
        PKCS10CertificationRequest csr = builder.build(signGen);

        File file = new File("/Users/long3/cert/usefullc.cer");
        FileOutputStream outputStream = new FileOutputStream(file);

        // 输出 PEM 格式的 CSR
        OutputStreamWriter output = new OutputStreamWriter(outputStream);
        JcaPEMWriter pem = new JcaPEMWriter(output);
        pem.writeObject(csr);
        System.err.println("=============CA证书生成==============");
        pem.close();

    }
}
